import _ from 'lodash'

const mixin = {
  props: ['query'],
  methods: {
    getColumnValue(item, path) {
      return _.get(item, path, 'N/A')
    },
    refresh(opt) {
      // if opt is MouseEvent ignore it
      if (opt instanceof MouseEvent) {
        opt = this.options
      }
      opt = opt ? opt : this.options
      this.isLoading = true
      this.selected = []
      this.fetchData(opt)
          .then(response => {
            let data = response.data
            this.items = data.data
            this.links = data.links
            this.meta = data.meta
            this.totalItems = data.meta.total
            this._updatePagination()
          })
          .finally(() => {
            this.isLoading = false
          })
    },
    _updatePagination() {
      let _m = this.meta
      this.footerProps.pagination = Object.assign(
          {},
          this.footerProps.pagination,
          {
            page: _m.current_page,
            itemsPerPage: _m.per_page,
            pageStart: _m.from - 1,
            pageStop: _m.to,
            pageCount: _m.last_page,
            itemsLength: _m.total
          }
      )
      this.footerProps.options = Object.assign({}, this.footerProps.options, {
        page: _m.current_page,
        itemsPerPage: _m.per_page
      })
    }
  },
  watch: {
    options: {
      handler(opt) {
        let _opt = _.clone(opt)
        _opt.query = this.query
        this.refresh(_opt)
      },
      deep: true
    },
    query: _.debounce(function (val) {
      this.options.query = val
      this.options.page = 1
    }, 800)
  },
  data() {
    return {
      options: {
        rowsPerPageItems: [10, 15, 20, 50],
        query: this.query
      },
      footerProps: {
        options: {
          page: 1,
          itemsPerPage: 10
        },
        pagination: {
          page: 1,
          itemsPerPage: 10,
          pageStart: 1,
          pageStop: 10,
          pageCount: 0,
          itemsLength: 0
        },
        'items-per-page-options': [10, 15, 20],
        'items-per-page-text': '每页',
        'items-per-page-all-text': '共'
      },
      isLoading: true,
      totalItems: 0,
      selected: [],
      links: {},
      meta: {},
      items: []
    }
  }
}

export default mixin
